﻿using System;
using System.Net;
using System.Text.RegularExpressions;

using EmbeddedSensorCloud.HTTP;

namespace EmbeddedSensorCloud.Plugin.MicroERP
{
    public class DeleteCustomerCommand : ICommand
    {
        #region Fields

        private ICustomerDAO _CustomerDao;

        #endregion

        #region Constructor

        public DeleteCustomerCommand(ICustomerDAO customerDao)
        {
            this._CustomerDao = customerDao;
        }

        #endregion

        #region ICommand

        public bool CanExecute(Request param)
        {
            return (param.Method.ToUpperInvariant() == "DELETE" &&
                    Regex.IsMatch(param.Url, @"^/api/customer/[0-9]+$", RegexOptions.IgnoreCase));
        }

        public ResponseEntity Execute(Request param)
        {
            uint id;
            string[] urlParts = param.Url.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            if (urlParts.Length != 3 || !uint.TryParse(urlParts[2], out id))
            { throw new BadRequestException(); }

            this._CustomerDao.Delete(id);

            return new ResponseEntity(null, HttpStatusCode.NoContent);
        }

        #endregion
    }
}
